<?php

namespace app\controller;

use ali\Sms;
use app\BaseController;
use app\model\Admin;
use app\model\Plateform;
use think\facade\Cache;
use think\helper\Str;
use think\response\Json;

class Authorization extends BaseController
{
    public function adminLogin(): Json
    {
        try {
            if (!$this->request->isPost()) throw new \Exception("请求方式错误", 7001);
            $data = $this->request->post();
            //校验验证码
            if (!captcha_check($data['captcha'])) throw new \Exception("验证码错误", 7002);
            $admin = $this->app->make(Admin::class)->where(['account' => $data['username'], 'state' => 1])->hidden(['create_time', 'update_time'])->find();

            if (!$admin) throw new \Exception("账号不存在", 7003);
            if (!checkPassword($data['password'], $admin->encode, $admin->password)) throw new \Exception("密码错误", 7004);
            $admin->login_token = Str::random(32);
            $admin->verify_time = date("Y-m-d H:i:s", strtotime("+7 hours"));
            $admin->save();
            return $this->success($admin);
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), $e->getCode());
        }
    }

    public function checkAdminLogin(): Json
    {
        try {
            $auth = getAuthorization();
            $admin = $this->app->make(Admin::class)->where(['id' => $auth['id'], 'state' => 1, 'login_token' => $auth['token']])->find();
            if (empty($admin)) throw new \Exception("登录已过期", 7004);
            $timer = strtotime($admin->verify_time);
            if ($timer < time()) throw new \Exception("登录已过期", 7004);
            return $this->success($admin);
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), $e->getCode());
        }
    }

    public function modify(): Json
    {
        try {
            if (!$this->request->isPost()) throw new \Exception("请求方式错误", 7001);
            $data = $this->request->post();
            $auth = getAuthorization();
            $admin = $this->app->make(Admin::class)->where(['id' => $auth['id'], 'state' => 1, 'login_token' => $auth['token']])->find();
            if (empty($admin)) throw new \Exception("登录已过期", 7004);
            $timer = strtotime($admin->verify_time);
            if ($timer < time()) throw new \Exception("登录已过期", 7004);
            if (!checkPassword($data['oldPassword'], $admin->encode, $admin->password)) throw new \Exception("旧密码错误", 7004);
            $password = setPassword($data['newPassword']);
            $admin->password = $password['password'];
            $admin->encode = $password['encode'];
            $admin->save();
            return $this->success($admin);
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), $e->getCode());
        }
    }

    public function merchantLogin(): Json
    {
        try {
            if (!$this->request->isPost()) throw new \Exception("请求方式错误", 7001);
            //校验短信验证码
            $param = $this->request->post();
            $account = $this->app->make(Plateform::class)->where(['mobile' => $param['username']])->find();
            if (empty($account) || $account['state'] != 1) throw new \Exception("手机号不存在", 7002);
            if ($param['login'] == 0) {
                $code = Cache::get("merchant_login_{$param['username']}_code");
                if (empty($code)) throw new \Exception("验证码不存在或已过期！", 7002);
                if ($code != $param['password']) throw new \Exception("验证码错误", 7002);
                Cache::delete("merchant_login_{$param['username']}_code");
            } else {
                // 验证密码是否正确
                if (!checkPassword($param['password'], $account->encode, $account->password)) throw new \Exception("密码错误", 7002);
            }
            $account->token = Str::random(32);
            $account->last_time = date("Y-m-d H:i:s", strtotime("+7 day"));
            $account->save();
            return $this->success($account);
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), $e->getCode());
        }
    }

    public function merchantLoginCode(): Json
    {
        try {
            if (!$this->request->isPost()) throw new \Exception("请求方式错误", 7001);
            //校验验证码
            $mobile = $this->request->post('mobile');
            if (empty($mobile)) throw new \Exception("手机号不能为空", 7002);
            //查询是否为渠道登录手机号
            $account = $this->app->make(Plateform::class)->where(['mobile' => $mobile])->find();
            if (empty($account) || $account['state'] != 1) throw new \Exception("手机号不存在", 7002);
            $lastTime = strtotime(date("Y-m-d 23:59:59"));
            $ttl = $lastTime - time();
            $smsTimer = Cache::get("merchant_login_{$mobile}_timer", 0);
            if ($smsTimer > 5) throw new \Exception("短信发送次数过多", 7002);
            if ($this->request->ip() != "127.0.0.1") {
                $code = Str::random(6, 1);
                $send = Sms::sendSms($mobile, ["code" => $code], "SMS_474460088");
                if (empty($send) || strtolower($send['Code']) != "ok") throw new \Exception($send["Message"] ?? "短信发送失败", 7002);
            } else {
                $code = 123456;
                $send = ["Message" => "短信发送成功"];
            }
            Cache::set("merchant_login_{$mobile}_code", $code, 300);
            Cache::set("merchant_login_{$mobile}_timer", $smsTimer + 1, $ttl);
            return $this->success($send);
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), $e->getCode());
        }
    }

    public function checkMerchantLogin(): Json
    {
        try {
            $auth = getAuthorization();
            $admin = $this->app->make(Plateform::class)->where(['id' => $auth['id'], 'state' => 1, 'token' => $auth['token']])->find();
            if (empty($admin)) throw new \Exception("登录已过期", 7004);
            $timer = strtotime($admin->last_time);
            if ($timer < time()) throw new \Exception("登录已过期", 7004);
            return $this->success($admin);
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), $e->getCode());
        }
    }
}
